import electron from 'electron'
const localShortcut = require('electron-localshortcut')

let isDev: boolean = process.env.NODE_ENV === 'development'

const { app, BrowserWindow } = electron
const isMacOS = process.platform === 'darwin'

const devToolsOptions: electron.OpenDevToolsOptions = { mode: 'undocked' }

function toggleDevTools (win = BrowserWindow.getFocusedWindow()) {
  if (win) {
    const { webContents } = win
    if (webContents.isDevToolsOpened()) {
      webContents.closeDevTools()
    } else {
      webContents.openDevTools(devToolsOptions)
    }
  }
}

function devTools (win = BrowserWindow.getFocusedWindow()) {
  if (win) {
    toggleDevTools(win)
  }
}

function openDevTools (win = BrowserWindow.getFocusedWindow(), defaultShow = true) {
  if (win && defaultShow) {
    win.webContents.openDevTools(devToolsOptions)
  }
}

function refresh (win = BrowserWindow.getFocusedWindow()) {
  if (win) {
    win.webContents.reloadIgnoringCache()
  }
}

function inspectElements () {
  const win = BrowserWindow.getFocusedWindow()
  const inspect = () => {
    win !== null && win.webContents.devToolsWebContents.executeJavaScript('DevToolsAPI.enterInspectElementMode()')
  }

  if (win) {
    if (win.webContents.isDevToolsOpened()) {
      inspect()
    } else {
      win.webContents.once('devtools-opened', inspect)
      win.webContents.openDevTools()
    }
  }
}

const addExtensionIfInstalled = (name: string, getPath: (name: string) => string) => {
  const isExtensionInstalled = (name: string) => {
    return BrowserWindow.getDevToolsExtensions &&
      {}.hasOwnProperty.call(BrowserWindow.getDevToolsExtensions(), name)
  }

  try {
    if (!isExtensionInstalled(name)) {
      BrowserWindow.addDevToolsExtension(getPath(name))
    }
  } catch (_) { //
  }
}

interface Any {
  [ a: string ]: any
}

export default function () {
  if (!isDev) {
    return
  }

  app.on('browser-window-created', (event, win) => {
    win.webContents.once('devtools-opened', () => {
      // Workaround for https://github.com/electron/electron/issues/13095
      setImmediate(() => {
        win.focus()
      })
    })

    /// Workaround for https://github.com/electron/electron/issues/12438
    win.webContents.once('dom-ready', () => {
      openDevTools(win, true)
    })
  })

  app.on('ready', () => {
    addExtensionIfInstalled('Vue.js devtools', name => `${__dirname}/../../.devtools/chrome`)

    localShortcut.register('CmdOrCtrl+Shift+C', inspectElements)
    localShortcut.register(isMacOS ? 'Cmd+Alt+I' : 'Ctrl+Shift+I', devTools)
    localShortcut.register('F12', devTools)

    localShortcut.register('CmdOrCtrl+R', refresh)
    localShortcut.register('F5', refresh)
  })
}
